#!/anaconda3/envs/FEALPy/bin python3.8
# -*- coding: utf-8 -*-
# File: load_product_goods_code_details.py
# Author: Bryan SHEN
# E-mail: m18801919240_3@163.com
# Site: Shanghai, China
# Time: 2024/3/22 09:58
# File-Desp:

import pandas as pd
import requests
import re
import json
import time
from loguru import logger


# B端API接口地址
B_API_SERVER_GOODS_CODE = "http://10.111.29.99/platform-foundation-service/item-code/search-simple"
REMOTE_GOODS_CODE_PROPERTY_URL = '{}'.format(B_API_SERVER_GOODS_CODE)
GOODS_CODE_HEAD = {
    "Content-Type": "application/json; charset=UTF-8",
    'Connection': 'close',
    'ahs-language': 'en-US',
    'ahs-timezone': 'Asia/Shanghai'
}


def load_remote_goods_code_property(goods_code):
    """
    从B端接口获SKU属性
    :param sku_id: SKU ID
    :return:
    """
    starttime=time.time()
    try:
        param = {}
        param["itemCodes"] = goods_code
        # response = requests.post(B_API_SERVER_GOODS_CODE, json=param,headers=GOODS_CODE_HEAD,timeout=1.5)
        response = requests.post(B_API_SERVER_GOODS_CODE, json=param, headers=GOODS_CODE_HEAD, timeout=30)
        # print('response :',response)
        content = response.content
        resp = json.loads(content)
        if(resp['code']!=200):
            logger.error('调用B2B接口获取ppvlist属性发生异常：{}'.format(resp['resultMessage']))

        # logger.info("load b2b data use time @{} s".format(time.time() - starttime))
        # logger.info('resp is {}'.format(resp))
        return resp
    except Exception as e:
        logger.error('调用B2B接口获取ppvlist属性发生异常：{}'.format(e))


def get_goods_code_level():

    data = pd.read_excel("json-excel_1711008211816.xlsx")

    con = data.to_dict(orient="records")
    ppn_name_set = {}
    for c in con:

        # if c['ppnName'] not in ppn_name_set:
        if c['ppnId'] not in ppn_name_set:
            ppn_name_set[c['ppnId']] = {}
            ppn_name_set[c['ppnId']]["ppnName"] = c['ppnName']
            ppn_name_set[c['ppnId']]["pass"] = -1
            if c['isPreferred']:
                ppn_name_set[c['ppnId']]["pass"] = c['order']
            ppn_name_set[c['ppnId']]["id"] = [c['id']]
            ppn_name_set[c['ppnId']]["value"] = [c['value']]
            ppn_name_set[c['ppnId']]["order"] = [c['order']]
        else:
            if c['isPreferred']:
                ppn_name_set[c['ppnId']]["pass"] = c['order']
            ppn_name_set[c['ppnId']]["id"].append(c['id'])
            ppn_name_set[c['ppnId']]["value"].append(c['value'])
            ppn_name_set[c['ppnId']]["order"].append(c['order'])

    for ppn in con:
        ppn["pass_order"] = ppn_name_set[ppn['ppnId']]["pass"]
        if ppn["order"] <= ppn_name_set[ppn['ppnId']]["pass"]:
            ppn["pass"] = 1
        else:
            ppn["pass"] = 0

    data2 = pd.DataFrame(con)

    with pd.ExcelWriter("goods_code_judge.xlsx", engine='xlsxwriter') as writer:
        data2.to_excel(writer, sheet_name='sheet1', index=False)


if __name__ == '__main__':

    # get_goods_code_level()

    #### test ####
    gc_list = list(['217108301980454912', '217108427428027392', '217108267841357824'])
    txt4 = load_remote_goods_code_property(list(gc_list))
    logger.info("test data restult is : {}".format(txt4))

    # laptop_details = pd.read_excel("笔记本数据详情_2024_03_21.xlsx")
    # laptop_details = pd.read_excel("笔记本数据详情_2024_0101-0325.xlsx")
    # laptop_details = pd.read_excel("笔记本数据详情_2024_1201-1231.xlsx")
    laptop_details = pd.read_excel("笔记本数据详情_2024_0325-0331.xlsx")
    goods_codes = [gc[:-1] for gc in laptop_details['goods_code'].tolist()]
    res = load_remote_goods_code_property(goods_codes[:1])
    logger.info("test data restult is : {}".format(res))

    failed_goods_codes = []
    container = []

    fw = open("goods_code_details_0325-0331.json", "w", encoding="GBK")
    # fw = open("goods_code_details_0101-0325.json", "w", encoding="GBK")
    # fw = open("goods_code_details_23_1201-1231.json", "w", encoding="GBK")
    fw2 = open("failed_goods_code.txt", "w", encoding="GBK")

    for i, gc in enumerate(goods_codes):
        try:
            goods_code_details = load_remote_goods_code_property([gc])

            if i % 1000 == 0:
                logger.info("current item is : {}".format(i))
                logger.info("current goods_code is : {}".format(gc))
                logger.info("current goods_code_details is : {}".format(goods_code_details))
            # container.append(goods_code_details["data"])
            fw.write(json.dumps(goods_code_details["data"], ensure_ascii=False) + '\n')
        except Exception as e:
            time.sleep(3)
            logger.info("error: {}".format(e))
            failed_goods_codes.append(gc)
            fw2.write(gc + "\n")

    fw.close()
    fw2.close()

    # logger.info("goods_code_details samples is : {}".format(goods_code_details))
    # with open("goods_code_details_0101-0325.json", "w", encoding="GBK") as fw:
    #     for d in container:
    #         fw.write(json.dumps(d, ensure_ascii=False) + '\n')
    #
    # with open("failed_goods_code.txt", "w", encoding="GBK") as fw2:
    #     for gc in failed_goods_codes:
    #         fw2.write(gc + "\n")

